import axios from 'axios'
import router from 'src/router/'
import store, { getToken } from 'src/store/'
import { DELETE_USER } from 'src/store/constants'

const API_ROOT = 'https://conduit.productionready.io/api'
const API_ROOT_DEV = 'https://conduit.productionready.io/api'


const instance = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? API_ROOT : API_ROOT_DEV,
  timeout: 10000
})

instance.defaults.headers.post['Content-Type'] = 'application/json'
instance.defaults.headers.put['Content-Type'] = 'application/json'

instance.interceptors.request.use(
  config => {
    const token = getToken()
    token && (config.headers['Authorization'] = 'Token '+token)
    return config
  },
  error => Promise.reject(error)
)

instance.interceptors.response.use(
  res => res.status === 200 ? Promise.resolve(res) : Promise.reject(res),
  error => {
    const { response } = error
    const { status } = response
    if (status === 401) {
      store.commit(DELETE_USER)
      router.push({path: 'login'})
      console.log('登陆过期，请重新登录')
    }
    return Promise.reject(error)
  }
)

export default instance